package com.way.fileexplorer.fragments;

import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.way.fileexplorer.R;
import com.way.fileexplorer.activities.FileExploreActivity;
import com.way.fileexplorer.activities.FileListScrollListener;
import com.way.fileexplorer.activities.FilePasteActivity;
import com.way.fileexplorer.activities.FileSearchActivity;
import com.way.fileexplorer.activities.MultiSelectActivity;
import com.way.fileexplorer.adapters.CopyDestListAdapter;
import com.way.fileexplorer.adapters.FileListAdapter;
import com.way.fileexplorer.util.ActivityUtils;
import com.way.fileexplorer.util.FileSort;
import com.way.fileexplorer.util.FileType;
import com.way.fileexplorer.util.FileUtil;
import com.way.fileexplorer.util.Slog;
import com.way.fileexplorer.util.StorageUtil;

/**
 * The base fragment, when explore files, using this one.
 * 
 */

public class DetailedListFragment extends BaseFragment implements
        OnItemClickListener {
    private String TAG = "DetailedListFragment";
    protected FileExploreActivity mContext;
    private static DetailedListFragment mFragment;
    protected boolean mExternalPage;
    protected ListView mList;
    private View mListViewLayout;
    private TextView mEmptyView; // bug 199312
    protected FileListAdapter mAdapter;
    protected File mTopPath;
    private boolean mIsSelectMode;
    private ArrayList<File> mSelectedFiles = new ArrayList<File>();
    private TextView mSelectedCnt;
    private int mSortBy;
    public static final int MENU_COPY = 1;
    public static final int MENU_CUT = 2;
    public static final int MENU_DELETE = 3;
    public static final int MENU_CLEAR = 4;
    public static final int MENU_SHARE = 5;
    public static final int MENU_RENAME = 6;
    public static final int MENU_DETAIL = 7;
    public static final int PASTE_PATH = 11;
    public static final int RESULT_RESELECT = 12;
    public static final int MENU_MULTI_SELECT = 20;
    public static Handler sHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            BaseFragment current = mFragment.mContext.getCurrentFragment();
            switch (msg.what) {
            case FileSort.START_SORT:
                if (null != mFragment) {

                    if (current instanceof DetailedListFragment) {
                        ((DetailedListFragment) current).startSort();
                    } else {
                        Slog.e("current fragment is not DetailedListFragment");
                    }
                }
                break;
            default:
                break;
            }
        };
    };
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case FileUtil.REFREAH_FILELIST:
                Slog.i(TAG,"refresh the file list");
                mAdapter.refresh();
                break;
            default:
                break;
            }
        };
    };
    
    public DetailedListFragment() {
        mFragment = this;
    }
    
    protected void init(FileExploreActivity context) {
        mContext = context;
    }

    @Override
    public void onCreate(Bundle state) {
        super.onCreate(state);
        setHasOptionsMenu(true);
    }
    
    public void onResume(){
        super.onResume();
        if(mAdapter != null){
            mAdapter.refresh();
        }
        // bug 199312 begin
        // When language of the system changed, force the TextView to use correct language.
        if (mEmptyView != null) {
            mEmptyView.setText(R.string.empty_view_prompt);
        }
        // bug 199312 end
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_detailed_explore,
                container, false);

        if (view == null) {
            return super.onCreateView(inflater, container, savedInstanceState);
        } else {
            mList = (ListView) view.findViewById(R.id.detailed_file_list);
            mListViewLayout = view.findViewById(R.id.file_explore_layout);
            mEmptyView = (TextView) view.findViewById(R.id.file_explore_empty_view); // bug 199312
            mAdapter = FileListAdapter.getFileListAdapter(mContext, mList).attachFragment(this).initWithPath(mTopPath);
            // mAdapter.refresh(); // has been called in initWithPath(), so remove this.
            mList.setAdapter(mAdapter);
            mList.setOnItemClickListener((OnItemClickListener) this);
            mList.setOnCreateContextMenuListener(mFileListOnCreateContextMenuListener);
            // Bug 201542 Begin
            mList.setOnScrollListener(new FileListScrollListener(mAdapter));
            // Bug 201542 End
            return view;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
         mAdapter.execute(position);
    }

    @Override
    public void onAttach(Activity activity) {
        mContext = (FileExploreActivity) activity;
        super.onAttach(activity);
    }

    protected void updateExplorePath(File file) {
        if (file == null) {
            Slog.e("Can't update path because file is null.");
            throw new NullPointerException();
        }
        mContext.onPathChanged(file, mExternalPage);
        mContext.setTitle("testVersion");
    }

    @Override
    public boolean onBackPressed() {
        if(mAdapter == null){
            return false;
        }
        if (mAdapter.popupFolder()) {
            mEnableExit = true;
            return true;
        } else {
            mAdapter.notifyDataSetChanged();
            return false;
        }
    }

    @Override
    // TODO useless now.
    public void onSaveInstanceState(Bundle outState) {
        // int a = android.os.Build.VERSION
        if(outState != null && mAdapter != null){
            outState.putString(KEY_CURRENT_PATH, mAdapter.getCurrentString());
            outState.putString(KEY_TOP_PATH, mAdapter.getTopString());
            super.onSaveInstanceState(outState);
        }else if(outState == null){
            Log.e(TAG, "outState is null");
        }else{
            Log.e(TAG, "mAdapter is null");
        }


    }

    @Override
    // TODO useless now.
    public void restoreExplore(Bundle data) {
        if (data == null) {
            return;
        }
        mAdapter.setCurrentString(data.getString(KEY_CURRENT_PATH));
        mAdapter.setTopString(data.getString(KEY_TOP_PATH));
    };

    public void onPrepareOptionsMenu(Menu menu) {
        mContext.getMenuInflater().inflate(R.menu.detailed_list_menu, menu);
        MenuItem multiSelectItem = menu.findItem(R.id.file_menu_select_more);
        MenuItem sortItem = menu.findItem(R.id.file_menu_sort_type);
        if(mAdapter != null && mAdapter.getCount()>0){
            if(multiSelectItem != null){
                multiSelectItem.setEnabled(true);
            }
            if(sortItem != null){
                sortItem.setEnabled(true);
            }
        }else{
            if(multiSelectItem != null){
                multiSelectItem.setEnabled(false);
            }
            if(sortItem != null){
                sortItem.setEnabled(false);
            }
        }
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.searchfile:
            mContext.startActivity(new Intent().setClass(
                    mContext.getApplicationContext(), FileSearchActivity.class));
            return true;
        case R.id.file_menu_mkdir:
            FileUtil.mkdir(mAdapter.getCurrentPath(), mAdapter, mContext);
            return true;
        case R.id.file_menu_newfile:
            FileUtil.newfile(mAdapter.getCurrentPath(), mAdapter, mContext);
            return true;
        case R.id.file_menu_select_more:
            Intent intent = new Intent(mContext, MultiSelectActivity.class);
            intent.putExtra("path", mAdapter.getCurrentPath().getPath());
            intent.putExtra("position", mList.getFirstVisiblePosition());
            startActivityForResult(intent, MENU_MULTI_SELECT);
            return true;
        case R.id.file_menu_sort_type:
            AlertDialog.Builder sortTypeDialog = new AlertDialog.Builder(
                    mContext);
            sortTypeDialog.setTitle(R.string.menu_sort_type);
            final int sortType;
            final SharedPreferences settings = mContext.getSharedPreferences(
                    FileSort.FILE_SORT_KEY, 0);
            sortType = settings.getInt(FileSort.FILE_SORT_KEY,
                    FileSort.SORT_BY_NAME);
            int selectItem = FileSort.getFileListSort().getSelectItemByType(
                    sortType);
            mSortBy = selectItem;
            sortTypeDialog.setSingleChoiceItems(R.array.sort_type, selectItem,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int whichButton) {
                            mSortBy = whichButton;
                        }
                    });
            sortTypeDialog.setNegativeButton(R.string.sort_by_asc,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int whichButton) {
                            switch (mSortBy) {
                            case 0:
                                mSortBy = FileSort.SORT_BY_NAME;
                                break;
                            case 1:
                                mSortBy = FileSort.SORT_BY_TYPE;
                                break;
                            case 2:
                                mSortBy = FileSort.SORT_BY_TIME_ASC;
                                break;
                            case 3:
                                mSortBy = FileSort.SORT_BY_SIZE_ASC;
                                break;
                            }
                            settings.edit()
                                    .putInt(FileSort.FILE_SORT_KEY, mSortBy)
                                    .commit();
                            FileSort.getFileListSort().setSortType(mSortBy);
                            mAdapter.startSort();
                            mAdapter.notifyDataSetChanged();

                        }
                    });
            sortTypeDialog.setPositiveButton(R.string.sort_by_desc,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int whichButton) {
                            switch (mSortBy) {
                            case 0:
                                mSortBy = FileSort.SORT_BY_NAME_DESC;
                                break;
                            case 1:
                                mSortBy = FileSort.SORT_BY_TYPE_DESC;
                                break;
                            case 2:
                                mSortBy = FileSort.SORT_BY_TIME_DESC;
                                break;
                            case 3:
                                mSortBy = FileSort.SORT_BY_SIZE_DESC;
                                break;
                            }
                            settings.edit()
                                    .putInt(FileSort.FILE_SORT_KEY, mSortBy)
                                    .commit();
                            FileSort.getFileListSort().setSortType(mSortBy);
                            mAdapter.startSort();
                            mAdapter.notifyDataSetChanged();

                        }
                    });
            sortTypeDialog.show();
            return true;
        case R.id.file_menu_storage_status:
            FileUtil.getStorageStatus(mContext);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    private final OnCreateContextMenuListener mFileListOnCreateContextMenuListener = new OnCreateContextMenuListener() {
        @Override
        public void onCreateContextMenu(ContextMenu menu, View v,
                ContextMenuInfo menuInfo) {
            AdapterView.AdapterContextMenuInfo info;
            try {
                info = (AdapterView.AdapterContextMenuInfo) menuInfo;
            } catch (ClassCastException e) {
                return;
            }
            final int position = info.position;
            File selectedFile = (File) mAdapter.getItem(position);
            FileListMenuClickListener l = new FileListMenuClickListener(
                    selectedFile);
            if(selectedFile != null && selectedFile.canRead() && selectedFile.canWrite() ){
                menu.add(0, MENU_COPY, 0, R.string.menu_copy)
                .setOnMenuItemClickListener(l);
        menu.add(0, MENU_CUT, 0, R.string.menu_cut)
                .setOnMenuItemClickListener(l);
        menu.add(0, MENU_DELETE, 0, R.string.operate_delete)
                .setOnMenuItemClickListener(l);
        if (selectedFile.isDirectory()) {
            menu.setHeaderTitle(R.string.folder_option);
            menu.add(0, MENU_CLEAR, 0, R.string.operate_clear)
                    .setOnMenuItemClickListener(l);
        } else {
            menu.setHeaderTitle(R.string.file_option);
            menu.add(0, MENU_SHARE, 0, R.string.operate_share)
                    .setOnMenuItemClickListener(l);
        }
        menu.add(0, MENU_RENAME, 0, R.string.operate_rename)
                .setOnMenuItemClickListener(l);
        menu.add(0, MENU_DETAIL, 0, R.string.operate_viewdetails)
        .setOnMenuItemClickListener(l);
            }else{
                if (selectedFile.isDirectory()) {
                    menu.setHeaderTitle(R.string.folder_option);
                } else {
                    menu.setHeaderTitle(R.string.file_option);
                }
                menu.add(0, MENU_DETAIL, 0, R.string.operate_viewdetails)
                .setOnMenuItemClickListener(l);
            }
        }
    };


    public void startPasteMode(int position) {
        boolean bIsSdCard = false;
        if (position > 0) {
            bIsSdCard = true;
        }
        mContext.startActivityForResult(new Intent()
                .setClass(mContext.getApplicationContext(),
                        FilePasteActivity.class)
                .putExtra(StorageUtil.FILE_LIST, mSelectedFiles.toString())
                .putExtra(StorageUtil.SDCARD_TYPE, bIsSdCard),PASTE_PATH);
    }

    DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            ActivityUtils.startPasteMode(which);
        }
    };

    private final class FileListMenuClickListener implements
            MenuItem.OnMenuItemClickListener {
        private File mClickedFile;

        public FileListMenuClickListener(File selectedFile) {
            mClickedFile = selectedFile;
        }

        @Override
        public boolean onMenuItemClick(MenuItem item) {
            if (mClickedFile == null) {
                return false;
            }

            switch (item.getItemId()) {
            case MENU_COPY:
                FileUtil.copy(mContext, mClickedFile, false);
                if(StorageUtil.getExternalStorageState().equals("mounted")){
                    Builder builder = new AlertDialog.Builder(mContext);
                    builder.setTitle(R.string.select_destination);
                    BaseAdapter adapter = new CopyDestListAdapter();
                    builder.setAdapter(adapter, listener);
                    builder.create().show();
                }else{
                	ActivityUtils.startPasteMode(0);
                }
                
                return true;
            case MENU_CUT:
                FileUtil.copy(mContext, mClickedFile, true);
                if(StorageUtil.getExternalStorageState().equals("mounted")){
                	ActivityUtils.showDestSelectDialog(mContext, listener);
                }else{
                	ActivityUtils.startPasteMode(0);
                }
                
                return true;
            case MENU_DELETE:
                new AlertDialog.Builder(mContext)
                .setTitle(R.string.operate_delete)
                .setMessage(R.string.confirm_delete)
                .setPositiveButton(android.R.string.ok,
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog,
                                            int which) {
                                        // TODO Auto-generated method stub
                                                FileUtil.deleteSingleFile(mClickedFile, mContext,mHandler);
                                            }
                                })
                                .setNegativeButton(android.R.string.cancel, null)
                                .show();
                return true;
            case MENU_CLEAR:
                new AlertDialog.Builder(mContext)
                        .setTitle(R.string.operate_clear)
                        .setMessage(R.string.msg_issure_clear)
                        .setPositiveButton(android.R.string.ok,
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog,
                                            int which) {
                                        // TODO Auto-generated method stub
                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                // TODO Auto-generated method
                                                // stub
                                                FileUtil.clear(mClickedFile,mContext);
                                                mHandler.obtainMessage( FileUtil.REFREAH_FILELIST).sendToTarget();
                                            }
                                        }).start();
                                    }
                                })
                        .setNegativeButton(android.R.string.cancel, null)
                        .show();
                return true;
            case MENU_SHARE:
                Intent intent=new Intent(Intent.ACTION_SEND);
                String type = FileType.getFileType(mContext).getTypeByFile(mClickedFile);
                Uri uri = Uri.parse("file://" + mClickedFile.getPath());
                intent.setType(type);
                intent.putExtra(Intent.EXTRA_STREAM, uri);
                startActivity(Intent.createChooser(intent, mContext.getResources().getString(R.string.operate_share)));
                return true;
            case MENU_RENAME:
                FileUtil.rename(mClickedFile, mAdapter,mContext);
                return true;
            case MENU_DETAIL:
                FileUtil.viewDetails(mClickedFile,mContext);
                return true;
            default:
                return false;
            }
        }

    }

    @Override
    public void onFolderChanged() {
        if (null == mAdapter) {
            return;
        }
        setEmptyView(mAdapter.isEmptyFolder());
        mCurrentString = mAdapter.getCurrentString();

        if (mContext instanceof FileExploreActivity) {
            if (mContext.isCurrentFragment(this)) {
                mContext.setPathBarString(mCurrentString);
            }
        }
    }

    private void setEmptyView(boolean isEmpty) {
        if (isEmpty) {
            mListViewLayout.setVisibility(View.GONE);
            mEmptyView.setVisibility(View.VISIBLE);
        } else {
            mListViewLayout.setVisibility(View.VISIBLE);
            mEmptyView.setVisibility(View.GONE);
        }
    }

    public FileListAdapter getAdapter(){
        return mAdapter;
    }
    public void startSort() {
        mAdapter.startSort();
        mAdapter.notifyDataSetChanged();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
        case MENU_MULTI_SELECT:{
            if(data != null){
                ArrayList<File> selectedFiles = (ArrayList<File>)data.getSerializableExtra("selectedFiles");
                int operationType = data.getIntExtra("operation", -1);
                if (operationType == R.id.menu_delete) {
                    if (selectedFiles != null) {
                        FileUtil.delete(selectedFiles, mContext, mAdapter);
                    }
                } else if (operationType == R.id.menu_copy) {
                    if(StorageUtil.getExternalStorageState().equals("mounted")){
                        Builder builder = new AlertDialog.Builder(mContext);
                        builder.setTitle(R.string.select_destination);
                        BaseAdapter adapter = new CopyDestListAdapter();
                        builder.setAdapter(adapter, listener);
                        builder.create().show();
                    }else{
                        ActivityUtils.startPasteMode(0);
                    }
                }
            }
        }
        }
    }
    
    public void update(){
        if(!mCurrentString.equals(mTopString)){
            if(mAdapter instanceof FileListAdapter){
                ((FileListAdapter)mAdapter).refresh();
            }
        }
    }
}
